package fel.via.cz.thewolfofwallstreet.components;

import android.app.Activity;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import fel.via.cz.thewolfofwallstreet.R;

public class SharesListView {

    private Activity activity;
    private ListView listView;
    private List<String> list;
    private ArrayAdapter<String> adapter;

    public SharesListView(Activity activity) {
        this.activity = activity;
        this.listView = (ListView) activity.findViewById(R.id.lvMain);

        this.initialize();
    }

    private void initialize() {
        this.list = new ArrayList<String>();
        this.adapter = new ArrayAdapter<String>(this.activity, android.R.layout.simple_list_item_single_choice, list);
        this.listView.setAdapter(this.adapter);
        this.listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }

    public void setup(JSONArray json) {
        this.list.clear();

        for (int i = 0; i < json.length(); i++) {
            try {
                JSONObject company = json.getJSONObject(i);
                this.list.add(company.getString("name"));
            } catch (JSONException e) {
                Log.e("JSONObject error: ", e.toString());
            }
        }
        this.adapter.notifyDataSetChanged();
    }

    public void setOnItemClickListener(AdapterView.OnItemClickListener listener) {
        this.listView.setOnItemClickListener(listener);
    }

//    public void selectFirstItem() {
//        this.listView.setItemChecked(0, true);
//        this.listView.performItemClick(listView.getAdapter().getView(0, null, null), 0, listView.getItemIdAtPosition(0));
//    }

    public void selectSpecificItem(int index) {
        this.listView.setItemChecked(index, true);
        this.listView.performItemClick(listView.getAdapter().getView(index, null, null), index, listView.getItemIdAtPosition(index));
    }
}
